#define BLINKER_BLE
#include <Blinker.h>
#define JOY_1 "JOYKey"


#define FREQ  50
#define CHANNEL  0
#define RESOLVTION   8
#define SERVO   21

BlinkerText text1("text1");
BlinkerText text2("text2");
BlinkerText text3("text3");
BlinkerText text4("text4");

BlinkerButton Button1("BUTTON_1");
BlinkerButton Button2("BUTTON_2");
BlinkerButton Button3("BUTTON_3");


BlinkerJoystick JOY1(JOY_1);
int s;
int i;

int calculatePWM(int degree)
{
  int min_width = 0.5/20*pow(2,RESOLVTION);
  int max_width = 2.5/20*pow(2,RESOLVTION);
  return ((max_width-min_width)*degree/180+min_width);
}
void Button1_callback(const String & state)
{
   if(state == "on")
   {
    s=100;
   }
}
void Button2_callback(const String & state)
{
    if(state == "on")
   {
    s=500;
   } 
}
void Button3_callback(const String & state)
{
    if(state == "on")
   {
    s=1000;
   } 
}

void joystick1_callback(uint8_t xAxis, uint8_t yAxis)
{
   text1.print(xAxis);
   text2.print(yAxis);
   if(xAxis > 128)
   {
    text3.print("右转");
   }
   else if(xAxis < 128)
   {
    text3.print("左转");
   }
   else if(xAxis == 128)
   {
    text3.print("停止");
   }
   if(yAxis > 128)
   {
    text4.print("后退");
   }
   else if(yAxis < 128)
   {
    text4.print("前进");
   }
   else if(yAxis == 128)
   {
    text4.print("停止");
   }
   if(yAxis < 128)
   {
    for(i = 0;i<=180;i+=10)
    {
    ledcWrite(CHANNEL,calculatePWM(i));
    delay(s);
    ledcWrite(CHANNEL,calculatePWM(0));
    }
   }
    else if(yAxis > 128)
   {
    for(i = 180;i>=0;i-=10)
    {
    ledcWrite(CHANNEL,calculatePWM(i));
    delay(s);
    ledcWrite(CHANNEL,calculatePWM(180));
    }
   }
   else if(yAxis == 128)
   {
    ledcWrite(CHANNEL,calculatePWM(0));
   

   }
   
}

void setup() 
{ 
   Button1.attach(Button1_callback);
   Button2.attach(Button2_callback);
   Button3.attach(Button3_callback);
   ledcSetup(CHANNEL,FREQ,RESOLVTION);
   ledcAttachPin(SERVO,CHANNEL);
   Blinker.begin();  
   JOY1.attach(joystick1_callback);
}

void loop()
{
  Blinker.run();
}     